package com.dpj.servlet;

import com.dpj.pojo.User;
import com.dpj.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    private UserService userService =new UserService();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String member = req.getParameter("remember");
        User user=userService.selectByNameAndPassword(username,password);
        //中文，进行编号进行传递
        String encode = URLEncoder.encode(username, "utf-8");
        Cookie userCookie=new Cookie("username",encode);
        Cookie passwordCookie=new Cookie("password",password);
        if(user==null){
            req.setAttribute("msg","用户名或密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }else{
            if("1".equals(member)) {
                userCookie.setMaxAge(60*60*24);
                passwordCookie.setMaxAge(60*60*24);
            }else {
                userCookie.setMaxAge(0);
                passwordCookie.setMaxAge(0);
            }
            resp.addCookie(userCookie);
            resp.addCookie(passwordCookie);
            //将登陆成功后的user对象，存储到session
            req.getSession().setAttribute("user",user);
            resp.sendRedirect("/w9/brandServlet");

        }
    }
}
